import java.util.ArrayList;
import java.util.List;

/**
 *给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
 * 单词应该以字符串列表的形式返回，必要时用空格补位，但输出尾部的空格需要删除（不允许尾随空格）。
 * 每个单词只能放在一列上，每一列中也只能有一个单词。
 * 输入：s = "HOW ARE YOU"
 * 输出：["HAY","ORO","WEU"]
 * 解释：每个单词都应该竖直打印。
 *  "HAY"
 *  "ORO"
 *  "WEU"
 * */
public class LeetCode1324 {
    public List<String> printVertically(String s) {
        String[] words = s.split(" ");
        int n = words.length;
        int m = 0;
        ArrayList<String> ans = new ArrayList<>();
        for (String str: words) {
            if (str.length() > m) {
                m = str.length();
            }
        }
        char[][] chars = new char[m][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < words[i].length(); j++) {
                chars[j][i] = words[i].charAt(j);
            }
            for (int j = words[i].length(); j < m; j++) {
                chars[j][i] = ' ';
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = n-1; j >=0 ; j--) {
                if (chars[i][j] != ' '){
                    ans.add(String.copyValueOf(chars[i], 0, j + 1));
                    break;
                }
            }
        }
        return ans;
    }

    public List<String> printVertically2(String s) {
        String[] words = s.split(" ");
        int n = words.length;
        int m = 0;
        ArrayList<String> ans = new ArrayList<>();
        for (String str: words) {
            if (str.length() > m) {
                m = str.length();
            }
        }
        for (int i = 0; i < m; i++) {
            StringBuilder str = new StringBuilder();
            for (int j = 0; j < n; j++) {
                if (words[j].length() > i) {
                    str.append(words[j].charAt(i));
                } else {
                    str.append(' ');
                }
            }
            while (str.charAt(str.length()-1) == ' ') {
                str.deleteCharAt(str.length()-1);
            }
            ans.add(str.toString());
        }
        return ans;
    }
}
